package cn.lj.controller;


import cn.lj.domain.Product;
import cn.lj.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 查询产品列表
     * @return
     * @throws Exception
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<Product> list = productService.findAll();
        //把product对象存储到mv对象中,也会把user对象存入到request对象中
        mv.addObject("productList",list);
        //跳转页面
        mv.setViewName("product-list");
        return mv;
    }


    /**
     * 根据Id查询产品
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public ModelAndView findById(@RequestParam("id") int id){
        Product product = productService.findById(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("product",product);
        mv.setViewName("product-update");
        return mv;
    }

    /**
     * 根据productName模糊查询
     * @param productName
     * @return
     */
    @RequestMapping("/findAllByName")
    public ModelAndView findAllByName(@RequestParam("productName")String productName){
        ModelAndView mv = new ModelAndView();
        List<Product> list = productService.findAllByName(productName);
        mv.addObject("productList",list);
        mv.setViewName("product-list");
        return mv;
    }

    /**
     * 保存产品
     * @param product
     * @return
     * @throws Exception
     */
    @RequestMapping("/save")
    public String save(Product product) throws Exception {
        productService.save(product);
        return "redirect:findAll";
    }

    /**
     * 删除产品
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/delProduct")
    public String delProduct(int id) throws Exception{
        productService.delProduct(id);
        return "redirect:findAll";
    }

    /**
     * 更新产品
     * @param product
     * @return
     * @throws Exception
     */
    @RequestMapping("/update")
    public String update(Product product) {
        productService.update (product);
        return "redirect:findAll";
    }

}
